package com.yizhang.executor;

import com.yizhang.config.BoundSql;
import com.yizhang.pojo.Configuration;
import com.yizhang.pojo.MappedStatement;
import com.yizhang.utils.GenericTokenParser;
import com.yizhang.utils.ParameterMapping;
import com.yizhang.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-05-27 17:18:22
 * @Description: 执行sql
 */
public class SimpleExecutor implements Executor {

    private Connection connection = null;

    private PreparedStatement preparedStatement = null;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object parameter) throws Exception {
        // 打开数据库连接
        connection = configuration.getDataSource().getConnection();

        // 生成预编译对象
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        String finalSql = boundSql.getFinalSql();
        preparedStatement = connection.prepareStatement(finalSql);

        // 获取请求参数的class对象
        String parameterType = mappedStatement.getParameterType();
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);

            for (int i = 0; i < boundSql.getParameterMappingList().size(); i++) {
                ParameterMapping parameterMapping = boundSql.getParameterMappingList().get(i);
                String fieldName = parameterMapping.getContent();
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                Object value = declaredField.get(parameter);
                // 给sql中的?设置值
                preparedStatement.setObject(i + 1, value);
            }
        }

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        List<E> list = new ArrayList<>();
        while (resultSet.next()) {
            // 获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();

            // 创建一个ResultType对象用来返回数据
            String resultType = mappedStatement.getResultType();
            Class<?> aClass1 = Class.forName(resultType);
            Object o = aClass1.newInstance();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取column的值
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                // 给ResultType对象字段设置值
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, aClass1);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            list.add((E) o);
        }
        return list;
    }

    /**
     * 1.将#{property}替换成?
     * 2.保存property到ParameterMapping
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", handler);
        String finalSql = tokenParser.parse(sql);

        List<ParameterMapping> parameterMappingList = handler.getParameterMappings();
        return new BoundSql(finalSql, parameterMappingList);
    }
}
